class Poster {
	//获取图片信息
	async onImgInfo(url) {
		if (url.indexOf('https') === -1 && url.indexOf('http') > -1) {
			url = url.replace('http', 'https')
		}
		return new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: url,
				success: (res) => {
					// console.log(res)
					resolve(res)
				},
				fail: (err) => {
					console.log(url)
					console.log(err)
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '下载图片失败'
					})
				}
			})
		})
	}

	//画圆角矩形 x:离画布的x坐标，y:离画布的y坐标，w:圆角矩形的宽度，h:圆角矩形的高度，r:半径
	onRect(ctx, {
		x, y, w, h, r, color
	}) {
		ctx.translate(x, y)
		ctx.setFillStyle(color)
		ctx.beginPath(0);
		//右下角
		ctx.arc(w - r, h - r, r, 0, Math.PI * 0.5)
		ctx.lineTo(r, h);
		//左下角
		ctx.arc(r, h - r, r, Math.PI * 0.5, Math.PI);
		ctx.lineTo(0, r);
		//左上角
		ctx.arc(r, r, r, Math.PI, Math.PI * 1.5);
		ctx.lineTo(w - r, 0)
		//右上角
		ctx.arc(w - r, r, r, Math.PI * 1.5, 0);
		ctx.lineTo(w, h - r);
		ctx.closePath();
		ctx.fill()
	}
	
	//画头像，可以带边框，也可以修改边框颜色
	async onAvatar(ctx,{url,x,y,w,h,r,border,borderColor}){
		//边框大小
		if(!border) border = 0;
		//边框颜色
		if(!borderColor) borderColor = '#efefef';
		//画边框
		if(border > 0) {
			ctx.save();
			this.onRect(ctx,{
				x,y,w,h,r,color: borderColor,
			});
			ctx.restore()
		}
		ctx.save();
		this.onRect(ctx,{
			x: x + border,
			y: y + border,
			w: w - border * 2,
			h: h - border * 2,
			r: r - border,
			color: '#FFF',
		});
		ctx.clip()
		await this.onAspectFillImg(ctx,{
			url,
			w: w - border * 2,
			h: h - border * 2,
			x: 0,y: 0
		})
		ctx.restore();
	}
	
	//画文字
	onText(ctx,{content,color,fontSize,fontWeight,x,y}){
		if(!x) x = 0;
		if(!y) y = 0;
		if(!content) content = '你得画点什么';
		if(!color) color = '#000';
		if(!fontSize) fontSize = 18;
		if(!fontWeight) fontWeight = 'normal';
		ctx.font = `${fontWeight} ${fontSize}px sans-serif`;
		ctx.setFillStyle(color)
		ctx.fillText(content,x,y + Number(fontSize))
	}


	// 图片适配（aspectFill）
	//path:图片路径，img：{width,height}通过getImageInfo获取图片的宽高信息， w:要画的图片的宽度，h:高度，x:图片在画布上的x标
	async onAspectFillImg(ctx,{ url, w, h, x, y }) {
		let info = await this.onImgInfo(url);
		let { path } = info;
		let img = {
			height: info.height,
			width: info.width
		}
		var left, top, //左偏移值，上偏移值，
			width, height; //截取宽度，截取高度

		height = img.width * (h / w);
		if (height > img.height) {
			height = img.height;
			width = height * (w / h);
			left = (img.width - width) / 2;
			top = 0;
		} else {
			left = 0;
			top = (img.height - height) / 2;
			width = img.width
		}
		ctx.save();
		if (path.indexOf('static/img') != -1) {
			// path = '../../../' + path;
			path = '/' + path;
		}
		ctx.drawImage(path, left, top, width, height, x, y, w, h);
		ctx.restore();
	}

	//直接this点调用方法
	//x , y 绘制的坐标
	//maxWigth 绘制文字的宽度
	//lineHeight 行高
	//maxRowNum 最大行数
	canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum, fontSize = getPx(4.8)) {
		if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
			return;
		}
		// canvas.font = '20px Bold PingFang SC'; //绘制文字的字号和大小

		canvas.font = `bold ${fontSize}px sans-serif`;

		// 字符分隔为数组
		var arrText = text.split('');
		var line = '';
		var rowNum = 1
		for (var n = 0; n < arrText.length; n++) {
			var testLine = line + arrText[n];
			var metrics = canvas.measureText(testLine);
			var testWidth = metrics.width;
			if (testWidth > maxWidth && n > 0) {
				if (rowNum >= maxRowNum) {
					var arrLine = testLine.split('')
					arrLine.splice(-2)
					var newTestLine = arrLine.join("")
					newTestLine += "..."
					canvas.fillText(newTestLine, x, y);
					//如果需要在省略号后面添加其他的东西，就在这个位置写（列如添加扫码查看详情字样）
					//canvas.fillStyle = '#2259CA';
					//canvas.fillText('扫码查看详情',x + maxWidth-90, y);
					return
				}
				canvas.fillText(line, x, y);
				line = arrText[n];
				y += lineHeight;
				rowNum += 1
			} else {
				line = testLine;
			}
		}
		canvas.fillText(line, x, y);
	}

	//返回文本的宽度
	getTextWidth(canvas, text) {
		let width = canvas.measureText(text).width;
		return Number(width.toFixed(0));
	}

	//lineWidth: 虚线的厚度
	//color: 虚线的颜色
	//x: 虚线的X坐标
	//y: 虚线的Y坐标
	//length: 虚线的长度
	drawDottedLine(ctx, {
		lineWidth,
		color,
		x,
		y,
		length
	}) {
		lineWidth = lineWidth ? lineWidth : 4;
		color = color ? color : '#BBB';
		length = length ? length : 50;
		x = x ? x : 0;
		y = y ? y : 0;
		ctx.setLineDash([7, 4]);
		ctx.lineWidth = lineWidth;
		ctx.strokeStyle = color;

		ctx.beginPath();
		ctx.moveTo(x, y);
		ctx.lineTo(x + length, y);
		ctx.stroke();
	}
	
	//将图片保存到相册
	onSave(url) {
		return new Promise((resolve,reject) => {
			wx.saveImageToPhotosAlbum({
				filePath: url,
				success(res) {
					console.log('授权：',res)
					wx.showToast({
						title: '保存成功',
						duration: 500
					})
					resolve(res)
				},
				complete() {
			
				},
				fail: (err) => {
					uni.showModal({
						title: '提示',
						content: '用户拒绝授权访问本地相册将导致头像无法保存！如需继续操作，请点击确定前往开启授权。',
						success: res => {
							if(res.confirm){
								uni.openSetting()
							}
						}
					})
					console.log(err)
					reject(err)
				}
			})
		})
	}
}
export default new Poster();
